package cn.abdl.springsecurity.security;

import cn.abdl.springsecurity.entity.Result;
import cn.abdl.springsecurity.utiils.ServletUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomAccessFailedHandler implements AuthenticationFailureHandler {
    private Logger logger = LoggerFactory.getLogger(CustomAccessFailedHandler.class);

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        logger.info("登录失败:{}",exception.getMessage());
        Result result = Result.failure(500,"登录失败");
        if(exception instanceof UsernameNotFoundException){
            result.setMsg("用户名不存在");
        }
        if(exception instanceof LockedException){
            result.setMsg("用户冻结");
        }
        if(exception instanceof BadCredentialsException){
            result.setMsg("账户密码不正确");
        }
        if(exception instanceof DisabledException){
            result.setMsg("用户未启用");
        }
        ServletUtil.write(JSON.toJSONString(result));
    }
}
